package com.other;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by baiguantao on 2018/1/19.
 */
public class DemoImages {
    static  ExecutorService  executorService= Executors.newWorkStealingPool(4);

    public static void main(String[] args)  throws Exception{
        InputStreamReader isr=new InputStreamReader(new FileInputStream(new File("d:\\logs\\imgs.txt")));
        BufferedReader buffer=new BufferedReader(isr);
        String inputline="";
        List<Callable<Object>> list=new LinkedList<>();
        while((inputline=buffer.readLine())!=null){
            String[] str=inputline.replaceAll("'","").split(",");
            for (String path:str) {
                list.add(new Callable<Object>() {
                    @Override
                    public Object call() throws Exception {
                        return getImageAndSave(path);
                    }
                });

            }
        }

        isr.close();
        buffer.close();
        executorService.invokeAll(list);

    }

    public static String  getImageAndSave(String imagePath)  {
        try {
//            System.out.println("开始处理：" + imagePath);
            String realPath = imagePath.substring(imagePath.lastIndexOf("/"), imagePath.length());
            URL url = new URL(imagePath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(3 * 1000);
            conn.setRequestMethod("GET");

            InputStream is = conn.getInputStream();
            FileOutputStream fos = new FileOutputStream(new File("d:\\logs\\shenfenzheng\\" + realPath));
            byte[] b = new byte[1024];
            int len = 0;
            while (-1 != (len = is.read(b))) {
                fos.write(b, 0, len);
                fos.flush();
            }

            is.close();
            fos.close();
            System.out.println("处理完成：" + realPath);
            return "处理完成:"+imagePath;
        }catch (Exception e){
            System.out.println("异常订单-----------:"+imagePath);
            return "异常订单:"+imagePath;
        }

    }
}
